﻿namespace DependencyPropertyChangedSample.ComponentModel
{
    using System;
    using System.Windows;
    using System.Windows.Media.Animation;

    public class DependencyPropertyDistributionHelper<T> : DependencyObject
    {
        private readonly DependencyObject element;
        private readonly Action<DependencyObject, T> distributor;
        public DependencyPropertyDistributionHelper(DependencyObject element, Action<DependencyObject, T> distributor)
        {
            this.element = element;
            this.distributor = distributor;
        }

        public readonly static DependencyProperty TargetProperty = DependencyProperty.Register("Target", typeof(T), typeof(DependencyPropertyDistributionHelper<T>),
            new PropertyMetadata(
                default(T),
                (o, e) =>
                {
                    ((DependencyPropertyDistributionHelper<T>)o).Update(e);
                }
            )
        );


        private void Update(DependencyPropertyChangedEventArgs e)
        {
            this.distributor(this.element, (T)e.NewValue);
        }

        public T Target
        {
            get
            {
                return (T)GetValue(TargetProperty);
            }

            set
            {
                SetValue(TargetProperty, value);
            }
        }

        public void SetTargets(Timeline timeline)
        {
            Storyboard.SetTarget(timeline, this);
            Storyboard.SetTargetProperty(timeline, new PropertyPath(TargetProperty));
        }
    }
}
